import { UserOutlined, SyncOutlined, CopyOutlined, ArrowDownOutlined } from '@ant-design/icons'
import { Bubble } from '@ant-design/x'
import { Button, Flex, message, Space, Typography } from 'antd'
import type { GetProp, GetRef } from 'antd'
import React, { useRef, useState, useCallback, useEffect } from 'react'
import style from './ChatContent.module.scss'
import HeaderWelcome from './HeaderWelcome'
import MarkdownRenderer from './MarkdownRenderer'
import { useMessageList } from '../../hooks/useMessageList'
import { copyToClip } from '../../utils/copy'
import { useSubmitMsg } from '../../hooks/useSubmit'
import SelectModel from './SelectModel'
import { ChatPropsType } from '../../store/messageSlice'
import EmptyPrompt from './EmptyPrompt'
import { useScreenWidth } from '../../hooks/useScreenWidth'

// 定义角色样式和配置
const rolesAsObject: GetProp<typeof Bubble.List, 'roles'> = {
  ai: {
    placement: 'start',
    avatar: { icon: <UserOutlined />, style: { background: '#2196f3' } },
    typing: false,
    style: {
      maxWidth: 900,
      backgroundColor: 'transparent'
    },
    styles: {
      content: {
        backgroundColor: 'transparent',
        width: 800,
        padding: 0
      }
    }
  },
  user: {
    placement: 'end',
    styles: {
      content: {
        maxWidth: 700
      }
    }
  }
}

interface ChatContentProps {
  isMobile?: boolean
  onToggleMenu?: () => void
  isMenuOpen?: boolean
}

export default function ChatContent(props: ChatContentProps) {
  const { isMobile, onToggleMenu, isMenuOpen } = props
  const listRef = React.useRef<GetRef<typeof Bubble.List>>(null)
  const scrollRef = useRef<HTMLDivElement>(null)
  const sendMsg = useSubmitMsg()
  const width = useScreenWidth()
  const [isUserScrolling, setIsUserScrolling] = useState(false)
  const [showScrollButton, setShowScrollButton] = useState(false)
  const [isFadingOut, setIsFadingOut] = useState(false)
  const lastScrollTop = useRef(0)

  // 从 Redux 中读取消息列表
  const { currentChatList = [] } = useMessageList()

  // 复制消息
  const handleCopy = (content: string) => {
    copyToClip(content)
    message.success('复制成功')
  }

  // 重发
  const handleResend = (index: number) => {
    if (currentChatList && currentChatList?.length > 1) {
      // 获取用户的最近提问内容
      const userMessage = currentChatList[index - 1].content
      sendMsg(userMessage)
    }
  }

  // 检查是否接近底部
  const checkIfNearBottom = useCallback(() => {
    if (!scrollRef.current) return false
    const { scrollTop, scrollHeight, clientHeight } = scrollRef.current
    const threshold = 100 // 距离底部100px以内认为是接近底部
    return scrollHeight - scrollTop - clientHeight < threshold
  }, [])

  // 处理滚动事件
  const handleScroll = useCallback(() => {
    if (!scrollRef.current) return

    const currentScrollTop = scrollRef.current.scrollTop
    const isScrollingUp = currentScrollTop < lastScrollTop.current

    // 更新上次滚动位置
    lastScrollTop.current = currentScrollTop

    // 如果用户向上滚动，显示滚动按钮
    if (isScrollingUp) {
      setIsUserScrolling(true)
      setShowScrollButton(true)
    }

    // 如果用户滚动到底部，隐藏滚动按钮
    if (checkIfNearBottom()) {
      setIsUserScrolling(false)
      setShowScrollButton(false)
    }
  }, [checkIfNearBottom])

  // 滚动到底部
  const scrollToBottom = useCallback(() => {
    if (scrollRef.current) {
      setIsFadingOut(true)
      const scrollOptions = {
        top: scrollRef.current.scrollHeight,
        behavior: 'smooth' as ScrollBehavior
      }
      scrollRef.current.scrollTo(scrollOptions)
      setTimeout(() => {
        setIsUserScrolling(false)
        setShowScrollButton(false)
        setIsFadingOut(false)
      }, 300)
    }
  }, [])

  // 监听新消息
  useEffect(() => {
    if (!isUserScrolling && scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight
    }
  }, [currentChatList, isUserScrolling])

  // 处理消息的渲染
  const handelMessageRender = (item: ChatPropsType) => {
    if (item.role === 'user') return item.content
    return (
      <>
        {/* 推理内容 */}
        {item.reasoning_content && (
          <div className={style.reasoning}>
            {item.reasoning_content && (
              <MarkdownRenderer markdownContent={item.reasoning_content} />
            )}
          </div>
        )}
        {/* 回答内容 */}
        {item.content && <MarkdownRenderer markdownContent={item.content} />}
      </>
    )
  }

  useEffect(() => {
    console.log('isMenuOpen', isMenuOpen)
    console.log('isMobile', isMobile)
  }, [isMenuOpen, isMobile])

  return (
    <>
      {/* 遮罩层 */}
      {isMobile && isMenuOpen && (
        <div
          className={style.overlay}
          onClick={() => {
            console.log('overlay clicked')
            onToggleMenu?.()
          }}
        />
      )}
      <Flex vertical className={style.content}>
        {/* 选择模型 */}
        <SelectModel {...props} />

        <div className={style.scrollContainer} ref={scrollRef} onScroll={handleScroll}>
          <HeaderWelcome />

          {currentChatList.length === 0 && width > 1000 && <EmptyPrompt />}

          {currentChatList.length > 0 && (
            <div style={{ padding: '10px' }}>
              <Bubble.List
                ref={listRef}
                roles={rolesAsObject}
                items={currentChatList.map((item: ChatPropsType, i: number) => {
                  const isAI = item.role !== 'user'
                  return {
                    key: i,
                    role: isAI ? 'ai' : 'user',
                    messageRender: () => handelMessageRender(item),
                    header: isAI && (
                      <Space>
                        <Typography.Text strong style={{ fontSize: 16 }}>
                          ChatAntdX
                        </Typography.Text>
                        <Typography.Text>{item.createTime}</Typography.Text>
                      </Space>
                    ),
                    footer: isAI && (
                      <Space>
                        <Button
                          color="default"
                          variant="text"
                          size="small"
                          icon={<SyncOutlined />}
                          onClick={() => handleResend(i)}
                        />
                        <Button
                          color="default"
                          variant="text"
                          size="small"
                          icon={<CopyOutlined />}
                          onClick={() => handleCopy(item.content)}
                        />
                      </Space>
                    )
                  }
                })}
              />
            </div>
          )}
        </div>

        {/* 滚动到底部按钮 */}
        {(showScrollButton || isFadingOut) && (
          <Button
            className={`${style.scrollButton} ${isFadingOut ? style.fadeOut : style.fadeIn}`}
            shape="circle"
            icon={<ArrowDownOutlined />}
            onClick={scrollToBottom}
          />
        )}
      </Flex>
    </>
  )
}
